import { createRouter, createWebHistory } from 'vue-router'
import Login from '../components/Auth/Login.vue'
import Register from '../components/Auth/Register.vue'
import AdminDashboard from '../components/Admin/Dashboard.vue'
import RestaurantManagement from '../components/Admin/RestaurantManager.vue'

import UserDashboard from '../components/User/UserDashboard.vue'
import UserRestaurant from '../components/User/UserRestaurant.vue'
import ErrorPage from '../components/Common/ErrorPage.vue'

const routes = [
  { path: '/', redirect: '/login' },
  { path: '/login', component: Login, meta: { guest: true } },
  { path: '/register', component: Register, meta: { guest: true } },
  {
    path: '/admin',
    component: AdminDashboard,
    meta: { requiresAuth: true, requiresAdmin: true }
  },
  {
    path: '/restaurants',
    name: 'RestaurantManagement',
    component: RestaurantManagement
  },
  // 添加可选参数标识
  {
    path: '/user/restaurant/:restaurantId?', // 添加问号使参数可选
    name: 'RestaurantManagement',
    component: () => import('@/components/User/UserRestaurant.vue'),
    meta: { requiresAuth: true }
  },

  {
    path: '/user',
    component: UserDashboard,
    meta: { requiresAuth: true }
  },
  // router.js
  {
    path: '/department/:departmentId/dishes',
    name: 'DepartmentDishes',
    component: () => import('@/components/User/DepartmentDishes.vue'),
    props: true
  },
  {
    path: '/user/restaurant/:restaurantId',
    name: 'RestaurantDetail',
    component: () => import('@/components/User/UserRestaurant.vue'),
    props: true
  },
  {
    path: '/user/restaurant/:id',
    component: UserRestaurant,
    meta: { requiresAuth: true }
  },
  { path: '/:pathMatch(.*)*', component: ErrorPage }
]

const router = createRouter({
  history: createWebHistory(),
  routes
})

router.beforeEach((to, from, next) => {
  const token = localStorage.getItem('token')
  const isAdmin = localStorage.getItem('isAdmin') === 'true'

  // // 已登录用户访问登录/注册页时重定向
  // if (to.meta.guest && token) {
  //   return next(isAdmin ? '/admin' : '/user')
  // }

  // // 需要登录的页面
  // if (to.meta.requiresAuth) {
  //   if (!token) {
  //     return next('/login')
  //   }
    
  //   // 需要管理员权限的页面
  //   if (to.meta.requiresAdmin && !isAdmin) {
  //     return next('/user')
  //   }
  // }

  next()
})

export default router